from app.extensions import scheduler
from flask import Flask
import platform
import atexit

app = None

# 创建app
def create_app(config=None):
    global app
    app = Flask(__name__)
    # 导入flask配置 -> 这里根据自己的项目导入配置就好哇
    # config = Config.get_config_from_host(app.name)
    app.config.from_object(config)
    # 初始化调度器配置    
    configure_scheduler(app)
    # scheduler_init(app)
    from app import test_api
    return app

def configure_scheduler(app):
    """Configure Scheduler"""
    scheduler.init_app(app)
    scheduler.start()
    # 加载任务，选择了第一次请求flask后端时加载，可以选择别的方式...
    @app.before_first_request   
    def load_tasks():
        # 开启任务
        from app import run_tasks


def scheduler_init(app):
    """保证系统只启动一次定时任务"""
    if platform.system() != 'Windows':
        fcntl = __import__("fcntl")
        f = open('scheduler.lock', 'wb')
        try:
            fcntl.flock(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
            scheduler.init_app(app)
            scheduler.start()
            app.logger.debug('Scheduler Started,---------------')
        except:
            pass

        def unlock():
            fcntl.flock(f, fcntl.LOCK_UN)
            f.close()
        atexit.register(unlock)
    else:
        msvcrt = __import__('msvcrt')
        f = open('scheduler.lock', 'wb')
        try:
            msvcrt.locking(f.fileno(), msvcrt.LK_NBLCK, 1)
            # scheduler.init_app(app)
            # scheduler.start()
            # app.logger.debug('Scheduler Started,----------------')
        except  Exception as e:
            scheduler.init_app(app)
            scheduler.start()
            print("Scheduler Started,----------------")

        def _unlock_file():
            try: 
                f.seek(0)
                msvcrt.locking(f.fileno(), msvcrt.LK_UNLCK, 1)
            except:
                pass

        atexit.register(_unlock_file)

    @app.before_first_request   
    def load_tasks():
        # 开启任务
        from app import run_tasks